<template>
  <div class="meter-type-selector">
    设备类型：
    <el-select style="width: 5rem;" v-model="selectedType" placeholder="请选择表计类型" @change="handleTypeChange">
      <el-option :value="1" label="水表" />
      <el-option :value="2" label="电表" />
      <el-option :value="3" label="气表" />
      <el-option :value="6" label="压力表" />
    </el-select>
  </div>
</template>

<script setup>
import { useMeterStore } from "@/stores/meter";
import { useCompanyStore } from "@/stores/company";
import { ref, watch, onMounted, defineExpose } from "vue";
import { handleError } from "../../utils/handleError";

const meterStore = useMeterStore();
const companyStore = useCompanyStore();
const loading = ref(false);


const emit = defineEmits(['meters-loaded']);

const selectedType = ref(1);

// 监听公司变化
watch(() => companyStore.currentCompany, () => {
  fetchMeterList(selectedType.value);
});

// 处理表计类型变化
async function handleTypeChange(value) {
  await fetchMeterList(value);
}

// 获取表计列表
async function fetchMeterList(type) {
  loading.value = true;
  try {
    await meterStore.fetchMeterList({
      company_id: companyStore.currentCompany.id,
      type: type
    });

    // 如果有表计数据，默认选择第一个表计
    if (meterStore.treeDataForChart.length > 0) {
      meterStore.setCurrentMeter(meterStore.treeDataForChart[0]);
    }

    // 发送表计列表加载完成事件，直接传递获取到的表计列表
    emit('meters-loaded', meterStore.meterList);
    return meterStore.meterList;
  } catch (error) {
    handleError(error, '获取表计列表失败');
  } finally {
    loading.value = false;
  }
}

async function refresh() {
  await fetchMeterList(selectedType.value);
}
//暴露给父组件的方法
defineExpose({
  refresh
});

// 组件挂载时获取表计列表
onMounted(async () => {
  await fetchMeterList(selectedType.value);
});
</script>

<style scoped>
.meter-type-selector {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
</style>